package cn.mafangui.hotel.controller.worker;

import cn.mafangui.hotel.entity.*;
import cn.mafangui.hotel.enums.OrderStatus;
import cn.mafangui.hotel.mapper.*;
import cn.mafangui.hotel.response.AjaxResult;
import cn.mafangui.hotel.response.MsgType;
import cn.mafangui.hotel.response.ResponseTool;
import cn.mafangui.hotel.service.OrderService;
import cn.mafangui.hotel.service.RoomService;
import cn.mafangui.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 订单接口
 */
@RestController
@RequestMapping(value = "/op/order")
@CrossOrigin("*")
public class OpOrderController {
    @Autowired
    private OrderService orderService;

    @Resource
    UserService userService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserVipLevelMapper userVipLevelMapper;
    @Resource
    RoomTypeMapper roomTypeMapper;
    @Resource
    RoomMapper roomMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RoomService roomService;

    /**
     * 添加预订
     * 订单状态默认为未付款状态
     */
    @RequestMapping(value = "/add")
    @Transactional
    public AjaxResult addOrder(int orderTypeId,String orderType, int userId,String name, String phone,int roomTypeId,String orderStatus, String roomType,
                        @DateTimeFormat(pattern = "yyyy-MM-dd") Date orderDate, Integer orderDays, Double orderCost,String roompassword){
        Order order = new Order(0,orderTypeId,orderType,userId,name,phone,roomTypeId,
                roomType,orderDate,orderDays, OrderStatus.UNPAID.getCode(),orderCost,roompassword);
        order.setOrderStatus(Integer.parseInt(orderStatus));

        List<Room> rooms = roomService.selectByType(roomTypeId);
        for (Room room : rooms) {
            if (room.getRoomStatus() == 1){
                order.setRoomNumber(room.getRoomNumber());
                room.setRoomStatus(0);
                roomService.update(room);
                break;
            }
        }
        if (order.getRoomNumber() == null){
            return ResponseTool.failed("房间不足");
        }

        User user = userMapper.selectByUsernameAndPhone(name, phone);
        if (user == null){
            return ResponseTool.failed("不存在该用户");
        }
        order.setUserId(user.getUserId());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        int re = orderService.addOrder(order);
        if(re!=1) return ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success("添加成功.");
    }


    @RequestMapping(value = "/delete")
    public AjaxResult deleteOrder(int orderId){
        int re = orderService.delete(orderId);
        if(re!=1) return ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success("删除成功.");
    }


    @RequestMapping(value = "/update")
    public AjaxResult updateOrder(int orderId,int orderTypeId,String orderType, int userId,String name,String orderStatus, String phone,int roomTypeId, String roomType,
                           @DateTimeFormat(pattern = "yyyy-MM-dd") Date orderDate, Integer orderDays, Double orderCost,String roompassword){
        Order order = new Order(orderId,orderTypeId,orderType,userId,name,phone,roomTypeId,
                roomType,orderDate,orderDays, OrderStatus.UNPAID.getCode(),orderCost,roompassword);
        order.setOrderStatus(Integer.parseInt(orderStatus));
        int re =  orderMapper.updateByPrimaryKeySelective(order);
        if(re!=1) return ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success("修改成功");
    }

    /**
     * 订单支付
     * @param orderId
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/pay")
    public AjaxResult payOrder(int orderId){
        int re = orderService.payOrder(orderId);
        if(re!=1) return ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success("支付成功.");
    }

    /**
     * 发送房间密码
     * @param orderId
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/sendRoomPassword")
    public AjaxResult sendRoomPassword(int orderId){
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Room room = roomMapper.selectByNumber(order.getRoomNumber());
        order.setRoompassword(room.getRemark());
        orderMapper.updateByPrimaryKeySelective(order);
        return ResponseTool.success("发送成功.");
    }

    /**
     * 取消订单
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/cancel")
    public AjaxResult cancelOrder(int orderId){
        int re= orderService.cancelOrder(orderId);
        if(re!=1) return ResponseTool.failed(MsgType.FAILED);
        return ResponseTool.success("取消成功.");
    }

    /**
     * 订单超时
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/overtime")
    public int orderOver(int orderId){
        Order order = new Order(orderId,OrderStatus.OVERTIME.getCode());
        return orderService.update(order);
    }


    @RequestMapping(value = "")
    public AjaxResult getAllOrder(){
        return ResponseTool.success(orderService.AllOrders());
    }

    @RequestMapping(value = "/count")
    public AjaxResult getOrderCount(){
        return ResponseTool.success(orderService.getOrderCount());
    }

    /**
     * 根据userID查询所有订单
     * @param userId
     * @return
     */
    @RequestMapping(value = "/user/{userId}")
    public AjaxResult getByUser(@PathVariable  int userId){
        return ResponseTool.success(orderService.selectByUserId(userId));
    }


    /**
     * 根据订单号查询订单
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/{orderId}")
    public AjaxResult getById(@PathVariable Integer orderId){

        Order order = orderService.selectById(orderId);

        if (order.getUserId() == null || order.getUserId() == 0){
            return ResponseTool.success(order);
        }
        // 费用
//        User user = userService.selectById(order.getUserId());
//        if (user == null){
//            return ResponseTool.success(order);
//        }
//        RoomType type = roomTypeMapper.selectByPrimaryKey(order.getRoomTypeId());
//        double discount = 1.0;
//        for (UserVipLevel userVipLevel : userVipLevelMapper.findAll()) {
//            if (userVipLevel.getViplevel().equals(String.valueOf(user.getViplevel()))){
//                discount = userVipLevel.getDiscount();
//                break;
//            }
//        }
//        order.setOrderCost(order.getOrderDays() * type.getPrice() * discount);

        return ResponseTool.success(order);
    }

    /**
     * 根据姓名、预留手机号查找订单
     * 主要用于客户入住
     * @param name
     * @param phone
     * @return
     */
    @RequestMapping(value = "/withNameAndPhone")
    public AjaxResult getByNameAndPhone(String name,String phone){
        return ResponseTool.success(orderService.selectByNameAndPhone(name,phone));
    }

}
